import { setFObjectEditable, newPointFObject } from '@/js/utils/FabricControls';
import { getImageCoords, getCanvasCoords } from '@/js/utils/imageUtils';

// 检测任务的标注结果
export default class PointsInput {
    constructor(initialPoints = []) {
        this.tools_callback = {
            point: this.pointToolCallback.bind(this)
        };

        // 存储points的数据
        this.points_geom = [];

        // 定义默认工具
        this.tools = ['point'];
        this.mode = 'point';

        // 初始化时根据传入的二维数组创建geom对象
        this.initialPoints = initialPoints;
    }

    // 在bindCanvas方法中添加初始化逻辑
    bindCanvas(canvas, image, label_tools) {
        // 绑定canvas  
        this.canvas = canvas;
        this.image = image;

        // 初始化geom对象
        if (this.initialPoints.length > 0) {
            let points = this.initialPoints.map(point => {
                return {
                    x: point[0],
                    y: point[1]
                }
            });
            let canvas_points = getCanvasCoords(this.image, points);
            console.log('PointsInput::bindCanvas canvas_point = ', canvas_points);
            for (let i = 0; i < canvas_points.length; i++) {
                let point_geom = this.paintPoint({
                    left: canvas_points[i].x,
                    top: canvas_points[i].y
                });
                if (point_geom) {
                    this.points_geom.push(point_geom);
                    this.canvas.add(point_geom);
                }
            }
        }

        if (label_tools) {
            for (let tool_name in this.tools_callback) {
                let tool = label_tools[tool_name];
                let callback = this.tools_callback[tool_name];
                if (tool) {
                    tool.setCallback(callback);
                }
            }
        }

        // 刷新显示
        this.canvas.requestRenderAll();
        return true;
    }

    paintPoint(point_coord) {
        // console.log('paintPoint point_coord = ', point_coord);
        if (!this.image) {
            return;
        }

        let point_geom = newPointFObject(this.points_geom.length, point_coord);
        this.registerObjectEvents(point_geom);
        return point_geom;
    }

    //////////////////////////////////////////////////////////////////////////////////////
    // 工具回调函数，更新外部UI显示
    pointToolCallback(pt) {
        // console.log('LabelDetection::rectToolCallback rect = ', rect, ' this = ', this);
        if (pt) {
            let point_geom = this.paintPoint(pt);
            this.points_geom.push(point_geom);
            point_geom && this.canvas.add(point_geom);
        }
    }

    // 注册事件
    registerObjectEvents(object) {
        object.on('selected', this.onSelected.bind(this));
        object.on('modified', this.onModified.bind(this));
    }

    onSelected(event) {
        console.log(`onSelected event = `, event);
        if (event.target) {
            this.selectLabel(event.target.label_id, event.target);
        }
    }

    onModified(event) {
        console.log(`onModified event = `, event);
        event.e.stopPropagation(); // 阻止事件冒泡
    }

    selectLabel(label_id, target = null) {
        console.log(`selectLabel label_id = ${label_id}, target = `, target);
        // 在canvas中选择标签对象
        if (!(label_id in this.points_geom)) {
            return;
        }

        // 放置待选择的对象
        setFObjectEditable(target);
        this.canvas.setActiveObject(target);
        this.canvas.requestRenderAll();
    }

    deleteSelection() {
        // 删除选中的对象
        let activeObject = this.canvas.getActiveObject();
        // console.log(`deleteSelection activeObject = `, activeObject);
        if (activeObject) {
            // 从points_geom中移除对应的元素
            const index = this.points_geom.findIndex(p => p === activeObject);
            if (index !== -1) {
                this.points_geom.splice(index, 1);
            }

            // 从canvas中移除对象
            this.canvas.remove(activeObject);
            this.canvas.requestRenderAll();
        }
    }

    getPoints() {
        let points = this.points_geom.map(point => (
            {
                x: point.left,
                y: point.top
            })
        );
        let points_image = getImageCoords(this.image, points);
        // 对points_image的坐标值保留两位小数
        points_image = points_image.map(point => ({
            x: parseFloat(point.x.toFixed(2)),
            y: parseFloat(point.y.toFixed(2))
        }));
        return points_image;
    }
}
